import React, {useEffect, useState} from 'react';
import {instance} from "../api";
import Alert from "@material-ui/lab/Alert";
import Container from "@material-ui/core/Container";
import {makeStyles} from "@material-ui/core";
import {Link} from 'react-router-dom'
import CircularProgress from "@material-ui/core/CircularProgress";

const useStyles = makeStyles(theme => ({
    root: {
        marginTop: theme.spacing(6)
    },
}))

const UserActivation = props => {
    const uid = props.match.params.uid
    const token = props.match.params.token
    const classes = useStyles()
    const [loading, setLoading] = useState(true)
    const [errors, setErrors] = useState({})

    useEffect(() => {
        async function activate() {
            try {
                await instance.post('/users/activation/', {uid, token})
                setLoading(false)
            } catch (e) {
                if (e.response && e.response.status === 403) {  // 用户两次输入激活链接会抛403错误 - 重复激活
                    setErrors({'detail': '您的账号已经激活,请登录'})
                } else if (e.response && e.response.status === 400) { // bad request
                    setErrors({'detail': '无效链接,请输入正确链接或者重新激活'})
                } else { // 其他错误
                    setErrors({detail: '账户激活失败！请重新进行激活...'})
                }
                setLoading(false)
            }
        }

        activate()
    }, [uid, token])

    return (
        <Container className={classes.root}>
            {loading && <CircularProgress/>}

            {errors.detail && (
                <Alert severity="error">{errors.detail}</Alert>
            )}

            {!errors.detail && (
                <Alert severity="success">账号激活成功！请
                    <Link to="/login">登录</Link>
                </Alert>
            )}
        </Container>
    );
};

export default UserActivation;